package class_and_object.homework;

import java.util.Scanner;

/**
 * 实验12_8
 * @author haomin
 * @date 2022/05/25 16:35
 **/
public class test_12_8 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (true){
            try {
                System.out.print("请输入十六进制数：");
                String str = in.nextLine();
                if(str.equals("no")){
                    break;
                }
                System.out.println("该数转化为十进制数为："+hexToDecimal(str.toUpperCase()));
                System.out.println();
            }catch (HexFormatException e){
                System.out.println(e.getMessage());
                System.out.println();
            }
        }
        in.close();
    }


    private static int hexToDecimal(String str) throws HexFormatException{
        int ret = 0;
        for (int i = 0; i < str.length(); i++) {
            int num = 0;
            if(str.charAt(i) >= 'A' && str.charAt(i) <= 'F'){
                num = str.charAt(i) - 'A' + 10;
            }else if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                num = str.charAt(i) - '0';
            }else{
                throw new HexFormatException("该字符串不是十六进制数");
            }
            ret = ret * 16 + num;
        }
        return ret;
    }

    public static class HexFormatException extends Exception{
        public HexFormatException() {
            super();
        }

        public HexFormatException(String message) {
            super(message);
        }
    }
}